﻿using System;
using System.Collections.Generic;
using System.Windows;
using Telerik.Windows.Controls;
using Telerik.Windows.Data;
using TruckScale.Models;

namespace TruckScale.ViewModels
{
  public class SSFormViewModel : ViewModelBase
  {
    public string Theme { get; set; } = Global._weighConfig["Theme"];
    public string MainFontSize { get; set; } = Global._weighConfig["MainFontSize"];
    public DelegateCommand SaveCommand { get; set; }
    public DelegateCommand ShowInfoCommand { get; set; }
    public RadObservableCollection<WeighFormModel> WeighFormList1 { get; set; } = new RadObservableCollection<WeighFormModel>();
    public RadObservableCollection<WeighFormModel> WeighFormList2 { get; set; } = new RadObservableCollection<WeighFormModel>();
    public WeighFormModel SelectedWeighItem { get; set; }
    public SSFormViewModel()
    {
      var list = WeighFormModel.SelectAllField();

      foreach (var f in list)
      {
        if (f.IsActive) WeighFormList2.Add(f);
        else WeighFormList1.Add(f);
      }

      SaveCommand = new DelegateCommand(OnSaveCommandExecuted);
      ShowInfoCommand = new DelegateCommand(OnShowInfoCommandExecuted);
    }

    private void OnSaveCommandExecuted(object obj)
    {
      //排序并添加到列表
      var list = new List<WeighFormModel>();
      for (int i = 0; i < WeighFormList1.Count; i++)
      {
        if (WeighFormList1[i].WeighFormKey == "_bh" || WeighFormList1[i].WeighFormKey == "_ch")
        {
          WeighFormList1[i].IsActive = true;
          continue;
        }
        WeighFormList1[i].IsActive = false;
        WeighFormList1[i].SortNo = i;
        list.Add(WeighFormList1[i]);
      }
      for (int i = 0; i < WeighFormList2.Count; i++)
      {
        WeighFormList2[i].IsActive = true;
        WeighFormList2[i].SortNo = i;
        list.Add(WeighFormList2[i]);
      }
      //保存到数据库
      WeighFormModel.UpdateAllField(list);
    }
    private void OnShowInfoCommandExecuted(object obj)
    {
      RadWindow.Prompt(new DialogParameters
      {
        Header = "修改字段名称",
        OkButtonContent = "确定",
        CancelButtonContent = "取消",
        IconTemplate = null,
        Theme = StyleManager.GetTheme(Application.Current.MainWindow),
        Content = "将 " + SelectedWeighItem.WeighFormValue + " 修改为：",
        Closed = new EventHandler<WindowClosedEventArgs>(OnPromptClosed),
        Owner = Application.Current.MainWindow
      });
    }

    private void OnPromptClosed(object sender, WindowClosedEventArgs e)
    {
      if (e.PromptResult != null && e.PromptResult != string.Empty)
      {
        SelectedWeighItem.WeighFormValue = e.PromptResult;

        //刷新界面
        WeighFormList1.Reset();
        WeighFormList2.Reset();
      }
    }
  }
}
